# file_api.py
# 创建一个蓝图
import logging
from io import BytesIO

from flask import Blueprint, request, send_file
from werkzeug.datastructures import FileStorage

from common.models.responses import success_response, bad_request
from service.parse.file_service import FileService

api_bp = Blueprint('file', __name__)
# 日志
log = logging.getLogger('app')

file_service = FileService()

@api_bp.route('/upload', methods=['POST'])
def upload():
    """
    处理文件上传请求。

    返回:
    - 成功时返回成功的JSON响应
    - 发生异常时返回内部错误的JSON响应
    """
    if 'file' not in request.files:
        return bad_request('No file part')
    file: FileStorage = request.files['file']
    # 文件服务逻辑实现
    oss_object = file_service.upload(file)
    return success_response(data=oss_object.to_dict(), message=f'File {file.filename} successfully uploaded')


@api_bp.route('/download', methods=['GET'])
def download():
    """
    处理文件下载请求。

    参数:
    - object_id: 文件的唯一标识符

    返回:
    - 成功时返回文件流
    - 发生异常时返回内部错误的JSON响应
    """
    object_id = request.args.get('object_id')
    if not object_id:
        return bad_request('No object_id provided')

    try:
        file_stream = file_service.get_object(object_id)
        byte_stream = BytesIO(file_stream.read())
        return send_file(byte_stream, as_attachment=True, download_name=object_id)
    except Exception as e:
        log.error(f'Error downloading file: {e}')
        return bad_request(str(e))